import React, { Component } from 'react';
import {Form,Button,Input,NavBar,Toast} from 'antd-mobile'
import "./index.css"
import * as service from '../../api'
import {store} from '../../store'

class Login extends Component {

    //账号的自定义校验器
    checkMobile = (_, value) => {
        if (/^1[3-9]\d{9}$/.test(value)) {
            return Promise.resolve()
        }else{
            return Promise.reject(new Error('输入正确的手机号!'))
        }
    }
    //密码的自定义校验器
    checkPassword = (_, value) => {
        if (/^\d{4,}$/.test(value)) {
            return Promise.resolve()
        }else{
            return Promise.reject(new Error('输入正确的密码!'))
        }
    }
    //表单校验通过后执行
    async onFinish(values){
        console.log(values);
        //在这里发请求, 完成登陆
        var res = await service.user_login(values)
        if( res.data.code == 200 ){
            //弹出"登陆成功"
            Toast.show({content:'登陆成功!'});

            //保存token等关键信息( 触发action来保存token到store )
            //store.dispatch() 触发action并携带参数
            store.dispatch( { type:'SAVE_TOKEN',payload:res.data.data } )
            
            //跳转到主页;
            this.props.history.push('/index/home');
        }
    }
    onBack(){
        this.props.history.goBack();
    }
    render() {
        return (
            <div className='login'>
                <NavBar onBack={this.onBack.bind(this)}>标题</NavBar>
                <Form
                    layout='horizontal'
                    onFinish={this.onFinish.bind(this)}
                    footer={
                        <Button block type='submit' color='primary' size='large'>
                            立即登录
                        </Button>
                    }
                >
                    <Form.Item
                    name='loginname'
                    rules={[
                        // { required: true, message: '账号不能为空' },
                        { validator: this.checkMobile }
                    ]}
                    >
                        <Input  placeholder='请输入账号' />
                    </Form.Item>

                    <Form.Item
                    name='password'
                    rules={[
                        // { required: true, message: '密码不能为空' },
                        { validator: this.checkPassword }
                    ]}
                    >
                        <Input type='password'  placeholder='请输入密码' />
                    </Form.Item>

                </Form>
            </div>
        );
    }
}

export default Login;